using Godot;
using System;
using System.Collections.Generic;
using System.Linq;

// 1. 定义存档数据结构
public class SaveData
{
    public string FileName { get; set; }      // 文件名 (ID)
    public string DisplayName { get; set; }   // 玩家起的存档名
    public string CurrentLevelPath { get; set; } // 当前关卡路径
    public string LastPlayedTime { get; set; }   // 最后游玩时间
    
    // 你还可以扩展：比如 PlayerColor
    // public PlayerColor SavedColor { get; set; }
}

// 2. 存档管理器
public static class SaveSystem
{
    private const string SAVE_DIR = "user://saves/"; // Godot 的用户存档目录

    // 初始化目录
    public static void EnsureSaveDirectory()
    {
        if (!DirAccess.DirExistsAbsolute(SAVE_DIR))
        {
            DirAccess.MakeDirAbsolute(SAVE_DIR);
        }
    }

    // 保存游戏
    public static void SaveGame(SaveData data)
    {
        EnsureSaveDirectory();
        string path = SAVE_DIR + data.FileName + ".save";
        
        // 更新时间
        data.LastPlayedTime = DateTime.Now.ToString("yyyy-MM-dd HH:mm");

        // 序列化 (使用 Godot 内置的 Json 助手或 Dictionary)
        var dict = new Godot.Collections.Dictionary
        {
            { "FileName", data.FileName },
            { "DisplayName", data.DisplayName },
            { "CurrentLevelPath", data.CurrentLevelPath },
            { "LastPlayedTime", data.LastPlayedTime }
        };

        using var file = FileAccess.Open(path, FileAccess.ModeFlags.Write);
        file.StoreString(Json.Stringify(dict));
    }

    // 读取单个存档
    public static SaveData LoadGame(string fileName)
    {
        string path = SAVE_DIR + fileName + ".save";
        if (!FileAccess.FileExists(path)) return null;

        using var file = FileAccess.Open(path, FileAccess.ModeFlags.Read);
        string content = file.GetAsText();
        
        var json = Json.ParseString(content).AsGodotDictionary();

        return new SaveData
        {
            FileName = (string)json["FileName"],
            DisplayName = (string)json["DisplayName"],
            CurrentLevelPath = (string)json["CurrentLevelPath"],
            LastPlayedTime = (string)json["LastPlayedTime"]
        };
    }

    // 获取所有存档列表
    public static List<SaveData> GetAllSaves()
    {
        EnsureSaveDirectory();
        List<SaveData> saves = new List<SaveData>();
        
        using var dir = DirAccess.Open(SAVE_DIR);
        if (dir != null)
        {
            dir.ListDirBegin();
            string fileName = dir.GetNext();
            while (fileName != "")
            {
                if (!dir.CurrentIsDir() && fileName.EndsWith(".save"))
                {
                    // 去掉后缀获取 ID
                    string rawName = fileName.Replace(".save", "");
                    SaveData data = LoadGame(rawName);
                    if (data != null) saves.Add(data);
                }
                fileName = dir.GetNext();
            }
        }
        
        // 按时间倒序排列 (最近玩的在前面)
        return saves.OrderByDescending(s => s.LastPlayedTime).ToList();
    }

    // 删除存档
    public static void DeleteSave(string fileName)
    {
        string path = SAVE_DIR + fileName + ".save";
        if (DirAccess.DirExistsAbsolute(SAVE_DIR))
        {
            DirAccess.RemoveAbsolute(path);
        }
    }
}